<template>
  <div class="search">
    <Card>
      <Row @keydown.enter.native="handleSearch">
        <Form ref="searchForm" :label-width="90" :model="searchForm" inline>
          <Form-item label="报表名称" prop="report_name">
            <label>
              <Input
                v-model="searchForm.report_name"
                clearable
                placeholder="请输入报表名称"
                style="width: 200px"
                type="text"
              />
            </label>
          </Form-item>
          <Form-item class="br" style="margin-left:-35px;">
            <Button icon="ios-search" type="primary" @click="handleSearch">搜索</Button>
            <Button @click="handleReset">重置</Button>
          </Form-item>
        </Form>
      </Row>
      <Row class="operation">
        <Button icon="md-add" type="primary" @click="add">添加</Button>
        <Button icon="md-refresh" @click="getDataList">刷新</Button>
      </Row>
      <Row>
        <Table ref="table" :columns="columns" :data="data" :loading="loading" border>
          <template slot="action" slot-scope="{ row }">
            <a
              class="edit"
              size="small"
              style="color:#2d8cf0;font-size: 12px;"
              type="text"
              @click="designReport(row)"
            >设计报表</a>
            <Divider type="vertical"/>
            <a
              class="edit"
              size="small"
              style="color:#2d8cf0;font-size: 12px;"
              type="text"
              @click="edit(row)"
            >编辑</a>
            <Divider type="vertical"/>
            <a class="del" style="color:#ed4014;font-size: 12px;" @click="remove(row)">删除</a>
          </template>
        </Table>
      </Row>
    </Card>
    <Modal v-model="modalVisible" :mask-closable="false" :title="modalTitle" :width="700">
      <Form
        ref="form"
        :label-width="100"
        :model="form"
        :rules="formValidate"
        label-position="left"
      >
        <FormItem label="报表名称：" prop="report_name">
          <label>
            <Input v-model="form.report_name" clearable placeholder="请输入报表名称" style="width:100%"/>
          </label>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="treeModalVisible=false">取消</Button>
        <Button :loading="templateSubmitLoading" type="primary" @click="handleSubmitTemplate">提交</Button>
      </div>
    </Modal>
    <Modal v-model="designReportModal" :mask-closable="false" :width="900" title="设计报表">
      <Row class="operation">
        <Button type="primary" @click="treeAdd">添加子项</Button>
        <Button @click="addRoot">添加一级项</Button>
        <Button @click="delAll">删除</Button>
        <Button @click="getParentList(designID)">刷新</Button>
      </Row>
      <Row justify="start" type="flex">
        <Col :md="9">
        <Alert show-icon>
          当前选择编辑：
          <span class="select-title">{{ editTitle }}</span>
          <a v-if="form.id" class="select-clear" @click="cancelEdit">取消选择</a>
        </Alert>
        <div :style="{maxHeight: maxHeight}" class="tree-bar">
          <Tree
            ref="tree"
            :data="treeData"
            @on-check-change="changeSelect"
            @on-select-change="selectTree"
          ></Tree>
          <Spin v-if="treeLoading" fix size="large"></Spin>
        </div>
        </Col>
        <Col :md="13" style="margin-left:10px;">
        <Form ref="designForm" :label-width="100" :model="designForm" :rules="designFormValidate">
          <FormItem label="上级节点：" prop="parentTitle">
            <div style="display:flex;">
              <Input v-model="designForm.parentTitle" readonly style="margin-right:10px;"/>
              <!-- <Poptip transfer trigger="click" placement="right-start" title="选择上级节点" width="250">
                    <Button icon="md-list">选择分类</Button>
                    <div slot="content" style="position:relative;min-height:5vh">
                      <Tree :data="dataEdit" @on-select-change="selectTreeEdit"></Tree>
                      <Spin size="large" fix v-if="loadingEdit"></Spin>
                    </div>
                  </Poptip> -->
            </div>
          </FormItem>
          <FormItem label="名称：" prop="header_name">
            <Input v-model="designForm.header_name"/>
          </FormItem>
          <FormItem label="关联字段：" prop="tableNameCoolumn">
            <Cascader v-model="designForm.tableNameCoolumn" :data="tableNameColumn"></Cascader>
          </FormItem>
          <FormItem label="显示设置：" prop="is_show">
            <Select v-model="designForm.is_show">
              <Option value="1">显示</Option>
              <Option value="2">有数据显示</Option>
              <Option value="0">不显示</Option>
            </Select>
          </FormItem>
          <FormItem label="排序值：" prop="sort">
            <Tooltip content="值越小越靠前，支持小数" placement="right" trigger="hover">
              <InputNumber v-model="designForm.sort" :max="1000" :min="0"></InputNumber>
            </Tooltip>
          </FormItem>
          <Form-item class="br">
            <Button
              :loading="submitLoading"
              icon="ios-create-outline"
              type="primary"
              @click="submitEdit"
            >修改并保存
            </Button>
            <!-- <Button @click="treeHandleReset">重置</Button> -->
          </Form-item>
        </Form>
        </Col>
      </Row>
      <div slot="footer">
      </div>
    </Modal>
    <Modal
      v-model="treeModalVisible"
      :mask-closable="false"
      :styles="{top: '150px'}"
      :title="treeModalTitle"
      :width="500">
      <Form ref="formAdd" :label-width="90" :model="formAdd" :rules="treeFormValidate">
        <div v-if="showParent">
          <FormItem label="上级节点：">{{ designForm.parentTitle }}</FormItem>
        </div>
        <FormItem label="名称：" prop="header_name">
          <Input v-model="formAdd.header_name"/>
        </FormItem>
        <div v-if="showCascader">
          <FormItem label="关联字段：" prop="tableNameCoolumn">
            <Cascader v-model="formAdd.tableNameCoolumn" :data="tableNameColumn"></Cascader>
          </FormItem>
        </div>
        <div v-if="showIsShow">
          <FormItem label="显示设置：" prop="is_show">
            <Select v-model="formAdd.is_show">
              <Option value="1">显示</Option>
              <Option value="2">有数据显示</Option>
              <Option value="0">不显示</Option>
            </Select>
          </FormItem>
        </div>
        <FormItem label="排序值：" prop="sort">
          <Tooltip content="值越小越靠前，支持小数" placement="right" trigger="hover">
            <InputNumber v-model="formAdd.sort" :max="1000" :min="0"></InputNumber>
          </Tooltip>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="treeModalVisible=false">取消</Button>
        <Button :loading="treeSubmitLoading" type="primary" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {getAccountColumns, initAccountTableName} from '../../../api/account'
import {accountReportList, addAccountRoot, destroy, store, update, updateAccountRoot} from '../../../api/accountReport'

export default {
  data() {
    return {
      templateSubmitLoading: false,
      designReportModal: false,
      tableNameColumn: [],
      loading: true, // 表单加载状态
      modalType: 0, // 添加或编辑标识
      modalVisible: false, // 添加或编辑显示
      modalTitle: '', // 添加或编辑标题
      searchForm: {
        report_name: '',
      },
      form: {
        report_name: '',
      },
      // 表单验证规则
      formValidate: {
        report_name: [
          {required: true, message: '名称不能为空', trigger: 'blur'},
        ],
      },
      designForm: {
        report_name: '',
        is_show: '1',
      },
      // 表单验证规则
      designFormValidate: {
        report_name: [
          {required: true, message: '名称不能为空', trigger: 'blur'},
        ],
      },
      submitLoading: false, // 添加或编辑提交状态
      columns: [
        {
          type: 'index',
          width: 60,
          align: 'center',
        },
        {
          title: '报表名称',
          key: 'report_name',
          minWidth: 120,
        },
        {
          title: '最近修改时间',
          key: 'updated_at',
          minWidth: 120,
          sortable: true,
        },
        {
          title: '操作',
          slot: 'action',
          width: 200,
          fixed: 'right',
          align: 'center',
        },
      ],
      data: [], // 表单数据
      // tree
      treeLoading: false, // 树加载状态
      maxHeight: '500px',
      loadingEdit: false, // 编辑上级树加载状态
      treeModalVisible: false, // 添加显示
      selectList: [], // 多选数据
      selectCount: 0, // 多选计数
      showParent: false, // 显示上级标识
      showCascader: false, // 显示上级标识
      showIsShow: false, // 显示上级标识
      treeModalTitle: '', // 添加标题
      editTitle: '', // 编辑节点名称
      treeForm: {
        // 编辑对象初始化数据
        id: '',
        title: '',
        parentId: '',
        parentTitle: '',
        sort: 1,
      },
      formAdd: {
        // 添加对象初始化数据
        is_show: '1',
      },
      treeFormValidate: {
        // 表单验证规则
        title: [{required: true, message: '名称不能为空', trigger: 'blur'}],
        sort: [
          {
            required: true,
            type: 'number',
            message: '排序值不能为空',
            trigger: 'blur',
          },
        ],
      },
      treeSubmitLoading: false,
      treeData: [],
      dataEdit: [],
      designID: null,
    }
  },
  methods: {
    init() {
      this.getDataList()
      this.initTableName()
    },
    initTableName() {
      initAccountTableName().then((res) => {
        if (res.data) {
          this.tableNameColumn = res.data
        }
      })
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getDataList()
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      // 重新加载数据
      this.getDataList()
    },
    getDataList() {
      this.loading = true
      accountReportList(this.searchForm).then((res) => {
        this.loading = false
        if (res.data) {
          this.data = res.data
        }
      })
    },
    handleSubmit() {

    },
    handleSubmitTemplate() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.templateSubmitLoading = true
          if (this.modalType === 0) {
            delete this.form.id
            store(this.form).then((res) => {
              this.templateSubmitLoading = false
              if (res.data) {
                this.getDataList()
                this.modalVisible = false
              }
              this.$Message.success(res.message)
            })
          } else {
            // 编辑
            update(this.form, this.form.id).then((res) => {
              this.templateSubmitLoading = false
              if (res.data) {
                this.getDataList()
                this.modalVisible = false
              }
              this.$Message.success(res.message)
            })
          }
        }
      })
    },
    add() {
      this.modalType = 0
      this.modalTitle = '添加'
      this.$refs.form.resetFields()
      this.form = {report_name: ''}
      delete this.form.id
      this.treeData = []
      this.modalVisible = true
    },
    edit(v) {
      this.modalType = 1
      this.modalTitle = '编辑'
      this.$refs.form.resetFields()
      // 转换null为""
      for (const attr in v) {
        if (v[attr] === null) {
          v[attr] = ''
        }
      }
      const str = JSON.stringify(v)
      this.form = JSON.parse(str)
      this.modalVisible = true
    },
    remove(v) {
      this.$Modal.confirm({
        title: '确认删除',
        content: '您确认要删除 ' + v.report_name + ' ?',
        loading: true,
        onOk: () => {
          // 删除
          destroy(v.id).then((res) => {
            this.$Modal.remove()
            if (res.data) {
              this.getDataList()
            }
            this.$Message.success(res.message)
          })
        },
      })
    },
    designReport(row) {
      this.designID = row.id
      this.getParentList(this.designID)
      this.getParentListEdit(this.designID)
      this.designReportModal = true
    },
    // tree
    getParentList(v) {
      this.treeLoading = true
      getAccountColumns(v).then(res => {
        this.treeLoading = false
        if (res.data) {
          this.treeData = res.data
        }
      })
    },
    getParentListEdit(v) {
      getAccountColumns(v).then(res => {
        this.treeLoading = false
        if (res.data) {
          const aaa = res.data
          // 头部加入一级
          const first = {
            id: '0',
            title: '一级项目'
          }
          aaa.unshift(first)
          this.dataEdit = aaa
        }
      })
    },
    selectTree(v) {
      if (v.length > 0) {
        // 转换null为""
        for (const attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = ''
          }
        }
        const str = JSON.stringify(v[0])
        const data = JSON.parse(str)
        this.designForm = data
        this.editTitle = data.title
      } else {
        this.cancelEdit()
      }
    },
    cancelEdit() {
      const data = this.$refs.tree.getSelectedNodes()[0]
      if (data) {
        data.selected = false
      }
      this.$refs.form.resetFields()
      this.designForm.id = ''
      this.editTitle = ''
    },
    selectTreeEdit(v) {
      if (v.length > 0) {
        // 转换null为""
        for (const attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = ''
          }
        }
        const str = JSON.stringify(v[0])
        const data = JSON.parse(str)
        this.designForm.parent_id = data.id
        this.designForm.parentTitle = data.title
      }
    },
    treeHandleReset() {
      this.$refs.designForm.resetFields()
    },
    submitEdit() {
      this.$refs.designForm.validate((valid) => {
        if (valid) {
          if (!this.designForm.id) {
            this.$Message.warning('请先点击选择要修改的节点')
            return
          }
          this.submitLoading = true
          // 避免传入null字符串
          updateAccountRoot(this.designForm).then(res => {
            this.submitLoading = false
            if (res.data) {
              this.$Message.success(res.message)
              this.getParentList(this.designID)
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    },
    submitAdd() {
      this.$refs.formAdd.validate((valid) => {
        if (valid) {
          this.treeSubmitLoading = true
          this.formAdd.report_id = this.designID
          addAccountRoot(this.formAdd).then(res => {
            this.treeSubmitLoading = false
            if (res.data) {
              this.$Message.success(res.message)
              this.getParentList(this.designID)
              this.treeModalVisible = false
            } else {
              this.$Message.error(res.message)
            }
          })
        }
      })
    },
    treeAdd() {
      if (!this.designForm.id) {
        this.$Message.warning('请先点击选择一个节点')
        return
      }
      this.treeModalTitle = '添加子节点'
      this.showParent = true
      this.showCascader = true
      this.showIsShow = true
      this.formAdd = {
        parent_id: this.designForm.id,
        sort: 1,
        is_show: '1',
      }
      this.treeModalVisible = true
    },
    addRoot() {
      this.treeModalTitle = '添加一级项目'
      this.showParent = false
      this.showCascader = true
      this.showIsShow = true
      this.formAdd = {
        parent_id: 0,
        sort: 1,
        is_show: '1',
      }
      this.treeModalVisible = true
    },
    changeSelect(v) {
      this.selectCount = v.length
      this.selectList = v
    },
    delAll() {
      this.$Message.warning('暂不支持删除操作')
      // if (this.selectCount <= 0) {
      //   this.$Message.warning('您还未勾选要删除的数据')
      //   return
      // }
      // this.$Modal.confirm({
      //   title: '确认删除',
      //   content:
      //     '您确认要删除所选的 ' + this.selectCount + ' 条数据及其下级所有数据?',
      //   loading: true,
      //   onOk: () => {
      //     let ids = ''
      //     this.selectList.forEach(function (e) {
      //       ids += e.id + ','
      //     })
      //     ids = ids.substring(0, ids.length - 1)
      //     // this.deleteRequest("请求路径，如/tree/delByIds/" + ids).then(res => {
      //     //   this.$Modal.remove();
      //     //   if (res.success) {
      //     //     this.$Message.success("删除成功");
      //     //     this.selectList = [];
      //     //     this.selectCount = 0;
      //     //     this.cancelEdit();
      //     //     this.init();
      //     //   }
      //     // });
      //     // 模拟成功
      //     this.$Modal.remove()
      //     this.$Message.success('删除成功')
      //     this.selectList = []
      //     this.selectCount = 0
      //     this.cancelEdit()
      //   },
      // })
    },
  },
  mounted() {
    this.init()
  },
}
</script>
<style lang="less">
.operation {
  margin-bottom: 10px;
}

.select-clear {
  margin-left: 10px;
}

.drop-down {
  margin-left: 5px;
}

.vxe-select--panel {
  z-index: 9999 !important;
}

.my_table_insert .vxe-body--row.is--new {
  background-color: #f1fdf1;
}

.vxe-table--header {
  width: 100% !important;
}

.vxe-table--empty-placeholder {
  top: 48px !important;
}
</style>
